<template>
  <view class="shop-create">
    <uni-forms ref="shopForm" :rules="rules" @submit="handleCreateShop">
      <!-- 图片上传 -->
      <view class="addimage">
        <view>图片上传</view>
        <view style="margin-top: 20rpx;">
          <view v-if="shop.shopLogo" class="img-wrapper">
            <image style="width: 100%; height: 100%;" :src="shop.shopLogo"></image>
            <view class="close-icon" @click.stop="delImg">
              <uni-icons type="closeempty" size="20"></uni-icons>
            </view>
          </view>
          <view
            v-else
            class="camera"
            @click="chooseImage"
          >
            <uni-icons type="camera" size="40"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 店铺名称 -->
      <uni-forms-item label="店铺名称" required>
        <uni-easyinput
          v-model="shop.shopName"
          :inputBorder="false"
          placeholder="请输入店铺名称"
        />
      </uni-forms-item>

      <!-- 店铺描述 -->
      <uni-forms-item label="店铺描述" required>
        <uni-easyinput
          v-model="shop.shopDescription"
          :inputBorder="false"
          type="textarea"
          placeholder="请输入店铺描述"
        />
      </uni-forms-item>

      <!-- 提交按钮 -->
      <view class="form-group">
        <button @click="submitForm" class="submit-button">创建店铺</button>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { createShop } from '@/api/shop/index.js';

export default {
  data() {
    return {
      shop: {
        userId: 1,
        shopName: '',
        shopDescription: '',
        shopLogo: null, // 存储本地选择的图片路径
      },
    };
  },
  onLoad() {
  	this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    async getUserInfo() {
      try {
        const userInfo = this.$store.state.user;
        this.shop.userId = userInfo.userId;
      } catch (error) {
        console.error('获取用户信息失败:', error);
        uni.showToast({ title: '获取用户信息失败', icon: 'none' });
      }
    },

// 上传图片到服务器
async uploadImage(filePath) {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: 'http://localhost:8080/shop/upload', 
      filePath: filePath,
      name: 'file',
      success: (uploadResult) => {
        try {
          const res = JSON.parse(uploadResult.data);
          if (res.url) {
            console.log(res.url); // 正常值
            resolve(res.url); // 成功返回 URL
          } else {
            uni.showToast({ title: '图片上传失败', icon: 'none' });
            reject(new Error('图片上传失败，未返回 URL'));
          }
        } catch (error) {
          console.error('JSON 解析失败:', error);
          uni.showToast({ title: '图片上传失败', icon: 'none' });
          reject(error);
        }
      },
      fail: (err) => {
        console.error('图片上传失败:', err);
        uni.showToast({ title: '图片上传失败', icon: 'none' });
        reject(err);
      },
    });
  });
},

async chooseImage() {
  try {
    const res = await uni.chooseImage({
      count: 1, // 仅选择一张图片
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
    });

    if ( res[1] && res[1].tempFilePaths) {
      const tempFilePaths = res[1].tempFilePaths; // 正确获取 tempFilePaths
      if (tempFilePaths.length > 0) {
        this.shop.shopLogo = tempFilePaths[0]; // 保存第一张图片路径
      } else {
        uni.showToast({ title: '未选择图片或选择失败', icon: 'none' });
      }
    } else {
      uni.showToast({ title: '选择图片失败', icon: 'none' });
      console.error('返回值异常:', res);
    }
  } catch (err) {
    uni.showToast({ title: '选择图片失败', icon: 'none' });
    console.error('选择图片失败：', err);
  }
},


    // 删除图片
    delImg() {
      this.shop.shopLogo = null; // 删除已选择图片
    },

 async submitForm() {
   // 表单验证
   if (!this.shop.shopName || !this.shop.shopDescription) {
     uni.showToast({ title: '请填写完整信息', icon: 'none' });
     return;
   }
 
   if (!this.shop.shopLogo) {
     uni.showToast({ title: '请上传店铺 Logo', icon: 'none' });
     return;
   }
 
   try {
     // 上传图片
     const imageUrl = await this.uploadImage(this.shop.shopLogo); // 正确等待返回值
     console.log(imageUrl); 
     if (!imageUrl) {
       uni.showToast({ title: '图片上传失败，请重试', icon: 'none' });
       return;
     }
 
     // 更新图片 URL
     this.shop.shopLogo = imageUrl;
 
     // 提交表单数据
     const response = await createShop(this.shop);
     console.log(response);
 
     if (response === '店铺创建成功') {
       uni.showToast({ title: '店铺创建成功', icon: 'success' });
 
       // 销毁当前页面并跳转
       uni.redirectTo({
         url: `/pages/shop/myshop/myshop?userId=${this.shop.userId}`, // 确保 URL 使用正确参数
       });
     } else {
       uni.showToast({ title: response, icon: 'none' });
     }
   } catch (error) {
     console.error('创建店铺失败:', error);
     uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
   }
 }


  },
};
</script>



<style lang="scss" scoped>
.shop-create {
  padding: 16px;

  .addimage {
    margin-bottom: 20px;

    .img-wrapper {
      display: inline-block;
      position: relative;
      width: 100px;
      height: 100px;
      margin-right: 10px;

      .close-icon {
        position: absolute;
        top: -5px;
        right: -5px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        color: white;
        padding: 5px;
      }
    }

    .camera {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 100px;
      height: 100px;
      background: #f0f0f0;
      border: 1px dashed #ccc;
      border-radius: 4px;
    }
  }

  .form-group {
    margin-top: 20px;
  }

  .submit-button {
    width: 100%;
    padding: 10px;
    font-size: 16px;
    color: #fff;
    background-color: #007bff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
  }

  .submit-button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
  }
}
</style>
